<?php
    if(class_exists('UtWarehouse') === false)
    {
        Class UtWarehouse extends UtItemInfo implements UtItemInterface
        {

            private static $_instance = null;
            private $_account = "";
            private $_warehouseSize = 1200;
            private $_itemsVault = array();
            private static $_hexaF = "";
            private static $_hexa0 = "";
            private static $_freeSlot = array();
            private $_finalHexa = "";

            public function setWarehouseSize($size)
            {
                return $this->_warehouseSize = $size;
            }

            private function getWarehouseSize()
            {
                return $this->_warehouseSize;
            }

            private function getAccount()
            {
                if(empty($this->_account))
                    throw new Exception('Character Cannot be Empty');

                return $this->_account;
            }

            public function setAccount($acc)
            {
                if(empty($acc))
                {
                    throw new Exception('Account of the game cannot be Empty');
                }

                $this->_account = $acc;
                return $this;
            }

            public function deleteItemByHex($type,$id,$account = null)
            {
                $this->getWarehouseSize();
                ($this->_version == 2) ? $cortar = 32 : $cortar = 20;
                $tamanho = str_repeat("F",$cortar);
                if($account === null)
                {
                    $conta = mssql_query("SELECT memb___id from ".$this->_Db.".dbo.Memb_info");    
                }
                else
                {
                    $conta = mssql_query("SELECT memb___id from ".$this->_Db.".dbo.Memb_info where memb___id='".$account."'");
                }

                $num = mssql_num_rows($conta);
                for($x = 0; $x < $num ; $x++)
                {
                    $fetch = mssql_fetch_row($conta);
                    $query = mssql_query("SELECT CONVERT(TEXT, CONVERT(VARCHAR(".$this->_warehouseSize."), Items)) AS 'Warehouse' FROM ".$this->_Db.".dbo.warehouse WHERE AccountID = '" . $fetch[0] . "'");
                    if ($query) 
                    {
                        if ($character = mssql_fetch_object($query)) 
                        {
                            $character->Warehouse = strtoupper(bin2hex($character->Warehouse));
                            $items = str_split($character->Warehouse, $cortar);
                            (int)$coint=0;
                            foreach ($items as $id => $item) 
                            {
                                if($items[$id] == $tamanho)
                                {

                                }
                                else 
                                {   
                                    if($this->tipo($items[$id]) == $type && $this->id($items[$id]) == $id) 
                                    { 
                                        $items[$id] = $tamanho;
                                        $coint++;
                                    } 
                                }   
                            }
                            mssql_query("UPDATE ".$this->_Db.".dbo.warehouse SET Items = 0x" . implode('', $items) . " where AccountID='".$fetch[0]."'");
                        } 
                    }
                }

            }

            public function createWarehouse($account)
            {
                switch($this->_version == 1)
                {
                    case 1:
                        $tamanho = 1200;
                        $db = 2; 
                        break;
                    case 2:
                        $tamanho = 1920;
                        $db = 3;
                        break;    
                }
                $this->deleteWarehouse($account);
                $query = mssql_query("INSERT INTO ".$this->_Db.".dbo.warehouse (AccountID,items,Money,EndUseDate,DbVersion,pw) VALUES ('".$account."',convert(varbinary(".$tamanho."), replicate(0xFF, ".$tamanho.")), 0, getdate(), ".$db." , 0)");    

            }

            public function deleteWarehouse($account)
            {
                return mssql_query("DELETE FROM ".$this->_Db.".dbo.Warehouse where AccountID='".$account."'");
            }

            public function resetWarehouse()
            {
                for($a = 0 ; $a < 120 ; $a++)
                {
                    $this->setSlot($a,true);
                }
                return $this->updateWarehouse();
            }

            public function getItemFromWarehouse()
            {
                $this->getWarehouseSize();
                $this->getAccount();
                ($this->_version == 2) ? $tam = 32 : $tam = 20;
                self::$_hexaF = str_repeat("F",$tam);
                self::$_hexa0 = str_repeat("F",$tam);

                $tamanho = str_repeat("F",$tam);
                $query = mssql_query("SELECT CONVERT(TEXT, CONVERT(VARCHAR(".$this->_warehouseSize."), Items)) AS 'Inventory' FROM ".$this->_Db.".dbo.warehouse WHERE AccountID ='".$this->_account."'");
                if ($query) 
                {
                    if ($character = mssql_fetch_object($query)) 
                    {
                        $character->Inventory = strtoupper(bin2hex($character->Inventory));
                        $items = str_split($character->Inventory,$tam);
                        $check = array();
                        foreach ($items as $id => $item) 
                        {

                            $this->_itemsVault[$id]['VALUE'] = $items[$id];

                            $this->_itemsVault[$id]['X'] = $this->getItemPosX($this->getId($this->_itemsVault[$id]['VALUE']),$this->getType($this->_itemsVault[$id]['VALUE']));
                            $this->_itemsVault[$id]['Y'] = $this->getItemPosY($this->getId($this->_itemsVault[$id]['VALUE']),$this->getType($this->_itemsVault[$id]['VALUE']));
                            if($this->NoItem($this->_itemsVault[$id]['VALUE']) === true && array_key_exists($id,$check) === false)
                            {
                                $this->setSlot($id,true);
                                $this->_itemsVault[$id]['X'] = 0;
                                $this->_itemsVault[$id]['Y'] = 0;
                            }
                            else
                            {
                                for($p = 0; $p < $this->_itemsVault[$id]['X']; $p++)
                                {
                                    for($h = 0; $h < $this->_itemsVault[$id]['Y']; $h++)
                                    {
                                        $this->setSlot($id + $p,false);
                                        $this->setSlot($id + $p + 8 * $h,false);
                                        $check[$id + $p + 8 * $h] = $id + $p + 8 * $h;
                                        $check[$id + $p] = $id + $p;
                                    }
                                }
                            }
                        }
                        return true;
                    } 
                    else 
                    {
                        echo "Erro ao retornar Ba&uacute;";
                    }
                } 
                else
                {
                    echo "Erro executar comando sql";
                } 
            }

            public function returnItem()
            {
                $this->getItemFromWarehouse();
                foreach ($this->_itemsVault as $key => $value)
                {
                    if($this->NoItem($value['VALUE']) === true)
                    {

                    }
                    else
                    {
                        echo "<br /><a href=\"?removeSlot=".$key."\">" . $value['VALUE'] . "</a>";    
                    }

                }
            }

            public function removeItemFromSlot($slot)
            {
                $serial = $this->returnHexafromSlot($slot);
                $itemx = parent::getItemPosX(parent::getId($serial),parent::getType($serial));
                $itemy = parent::getItemPosY(parent::getId($serial),parent::getType($serial));

                $this->_itemsVault[$slot]['VALUE'] = self::$_hexaF;
                for($x = 0; $x < $itemx ; $x++)
                {
                    for($y = 0 ; $y < $itemy; $y++)
                    {
                        $this->setSlot($slot + $x,true);
                        $this->setSlot($slot + $x + 8 * $y,true);   
                    }
                }
            }

            public function returnHexafromSlot($slot)
            {
                return $this->_itemsVault[$slot]['VALUE'];
            }

            public function findSlot($item)
            {
                $item = trim($item);
                $itemx = parent::getItemPosX(parent::getId($item),parent::getType($item));
                $itemy = parent::getItemPosY(parent::getId($item),parent::getType($item));


                /*
                Utilizando Invez do Tamanho, utilizar Tamanho do Array de Itens
                if($this->_WareInv == 0)
                {
                $inicio = 0;
                $tamanho = 120;
                }
                else
                {   
                if($this->_version == 2)
                {
                $tamanho = 108;    
                }
                else
                {
                $tamanho = 76;
                }

                $inicio = 12;
                }
                */
                for($g = 0; $g < sizeof($this->_itemsVault); $g++)
                {
                    if($this->NoItem($this->_itemsVault[$g]['VALUE']) === true)
                    {
                        $error = 0;

                        if(($g + 1) % 8  == 0 && $itemx > 1) $error++;
                        if((g + 1) % 7  == 0 && $itemx > 2) $error++;
                        if((g + 1) % 6 == 0 && $itemx > 3) $error++;
                        if((g + 1) % 5 == 0 && $itemx > 4) $error++;

                        for($x = 0; $x < $itemx; $x++)
                        {
                            for($y = 0; $y < $itemy; $y++)
                            {
                                if($this->_itemsVault[$g + ($y * 8) + $x]['TAKEN'] == false)
                                    $error++;
                            }
                        }
                        if($error == 0)
                        {
                            self::$_freeSlot[] = $g;
                            $this->JumpSlot($g,$itemx,$itemy);
                            break 1;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                return ($error < 1) ?  true : false;
            }  

            public function jumpSlot($slot,$sizex,$sizey)
            {
                for($x = 0; $x < $sizex ; $x++)
                {
                    for($y = 0; $y < $sizey ; $y++)
                    {
                        $this->setSlot($slot + $x,false);
                        $this->setSlot($slot + $x + 8 * $y,false);  
                    }
                }
            } 

            public function setSlot($slot,$free = false)
            {
                if($free === false)
                {
                    $this->_itemsVault[$slot]['TAKEN'] = false;    
                }
                else
                {
                    $this->_itemsVault[$slot]['TAKEN'] = true;
                }

            }

            Public function insertItem($item)
            {
                //$this->getItemFromWarehouse();
                if($this->findSlot($item) === true)
                {
                    $this->_itemsVault[self::$_freeSlot[0]]['VALUE'] = $item;
                    array_shift(self::$_freeSlot);
                    return true;  
                }

                return false;
            }

            public function insertMultiplesItems($qtd)
            {
                //$this->getItemFromWarehouse();
                $itens = func_get_args();

                if($qtd > sizeof($itens[1]))
                {
                    throw new Exception('Low Hexadecimal for the Ammount of Itens');
                }

                array_shift($itens);
                $erro = 0;
                if(is_array($itens[0]))
                {
                    for($a = 0 ; $a < $qtd; $a++)
                    {
                        if(empty($itens[0][$a]) || $this->NoItem($itens[0][$a]) === true)
                        {
                            $erro++;
                            break;
                        }
                        elseif($this->findSlot($itens[0][$a]) == false)
                        {
                            $erro++;
                            break;
                        } 
                        $this->_itemsVault[self::$_freeSlot[0]]['VALUE'] = $itens[0][$a];
                        array_shift(self::$_freeSlot);  
                    }
                }
                else
                {
                    for($a = 0 ; $a < $qtd; $a++)
                    {
                        if(empty($itens[$a]) || $this->NoItem($itens[$a]) === true)
                        {
                            $erro++;
                            break;
                        }   
                        elseif($this->findSlot($itens[$a]) == false)
                        {
                            $erro++;
                            break;
                        } 
                        $this->_itemsVault[self::$_freeSlot[0]]['VALUE'] = $itens[$a];
                        array_shift(self::$_freeSlot);
                    }
                }
                return ($erro > 0) ? false : true;
            }

            public function itemToHexa()
            {
                $c = sizeof($this->_itemsVault);
                for($a = 0; $a <= $c ; $a++)
                {
                    $this->_finalHexa .= $this->_itemsVault[$a]['VALUE'];
                }
                return $this->_finalHexa;  
            }

            public function finish()
            {   
                $this->ItemToHexa();

                return $this->updateWarehouse();
            }

            private function updateWarehouse()
            {   
                unset($this->_itemsVault);
                $query = mssql_query("UPDATE ".$this->_Db.".dbo.warehouse set items=0x".$this->_finalHexa." where AccountId='".$this->_account."'");
                if($query)
                    return true;

                return false;   
            }

            public function noItem($value)
            {
                $error = 0;

                if(strtoupper($value) == self::$_hexaF) 
                    $error++;

                if($value == self::$_hexa0) 
                    $error++;

                if($value == NULL) 
                    $error++;

                if($error > 0)
                    return true;
                else
                    return false;
            }

            protected function __construct()
            {

            }

            public function __clone()
            {

            }

            public function clearVariable()
            {
                $this->_account = "";
                $this->_warehouseSize = 1200;
                $this->_itemsVault = array();
                self::$_hexaF = "";
                self::$_hexa0 = "";
                self::$_freeSlot = array();
                $this->_finalHexa = "";

            }

            public function __destroy()
            {
                $this->ClearVariable();
            }

            public static function getStance()
            {
                if(self::$_instance === null)
                    self::$_instance = new self;

                return self::$_instance;
            }

        }
    }
?>
